import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Card } from './models/card.entity';
import { DeepPartial, FindOptionsWhere, Repository } from 'typeorm';
// Repository是一个提供数据库操作的工具库
@Injectable()
export class CardService {
  // 注入Card实体
  constructor(
    @InjectRepository(Card) private CardRepository: Repository<Card>,
  ) {}
  // 返回值是promise对象
  // DeepPartial是一个将实体（Card）内部的所有属性加上?，即可以省略
  async create(entity: DeepPartial<Card>): Promise<boolean> {
    // const res = await this.CardRepository.insert(entity);//insert方法不会触发create事件
    const res = await this.CardRepository.save(
      this.CardRepository.create(entity), //create仅仅是创建一个内存实体，没有放入数据库
    ); //
    // console.log('res', res);
    if (res) {
      return true;
    }
    return false;
  }

  // 查询
  async findById(id: string): Promise<Card | null> {
    const res = await this.CardRepository.findOne({
      where: {
        id: id,
        // ...entity
      },
      relations: ['course', 'org'],
    });
    // console.log('res', res);
    return res;
  }

  // 修改
  async updateById(id: string, entity: DeepPartial<Card>): Promise<boolean> {
    const existEntity = await this.findById(id);
    if (!existEntity) {
      return false;
    }
    Object.assign(existEntity, entity);
    // const res = await this.CardRepository.update(id, entity);//这里update方法是不会触发entity的update事件的
    const res = await this.CardRepository.save(existEntity); //需要使用save
    if (res) {
      return true;
    }
    return false;
  }

  // 分页查询
  async findCards({
    // start,
    // size,
    where,
  }: {
    // start: number;
    // size: number;
    where: FindOptionsWhere<Card>;
  }): Promise<[Card[], number]> {
    const res = this.CardRepository.findAndCount({
      // take: size,
      // skip: start,
      where,
      order: {
        createAt: 'DESC',
      },
      relations: ['course', 'org'], //这里是关联表
    });
    return res;
  }

  // 硬删除
  // async del(id: string): Promise<boolean> {
  //   const res = await this.CardRepository.delete(id);
  //   if (res && res.affected && res.affected > 0) {
  //     return true;
  //   }
  //   return false;
  // }
  // 软删除
  async deleteById(id: string, userId: string): Promise<boolean> {
    const res1 = await this.CardRepository.update(id, {
      deleteBy: userId,
    });
    if (res1) {
      const res = await this.CardRepository.softDelete(id);
      if (res?.affected > 0) {
        return true;
      }
    }
    return false;
  }
}
